package org.dyk.mallmanagementsystem.service.orders;

import com.alibaba.fastjson.JSONObject;
import org.dyk.mallmanagementsystem.model.Goods;
import org.dyk.mallmanagementsystem.model.Orders;
import org.dyk.mallmanagementsystem.model.User;
import org.dyk.mallmanagementsystem.repository.GoodsRepository;
import org.dyk.mallmanagementsystem.repository.OrdersRepository;
import org.dyk.mallmanagementsystem.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OrdersServiceImpl implements OrdersService{
    @Autowired
    private OrdersRepository ordersRepository;
    @Autowired
    private GoodsRepository goodsRepository;
    @Autowired
    private UserRepository userRepository;

    /**
     * 查询所有订单 分页
     * @param pageable
     * @return
     */
    @Override
    public Page<Orders> findAll(Pageable pageable) {
        return ordersRepository.findAll(pageable);
    }

    /**
     * 根据 主键 获取订单详细信息
     * @param oid
     * @return
     */
    @Override
    public JSONObject findByOid(int oid) {
        //多表查询，并将字段添加到jsonObject数组内
        Orders orders = ordersRepository.findByOid(oid);
        Goods goods = goodsRepository.findByGid(orders.getGid());
        User user = userRepository.findByUid(orders.getUid());
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(goods);
        jsonObject.put("oid",orders.getOid());
        jsonObject.put("ordersDate",orders.getOrdersDate());
        jsonObject.put("userName",user.getUserName());
        jsonObject.put("goodsImg",goods.getGoodsImg());
        jsonObject.put("goodsName",goods.getGoodsName());
        jsonObject.put("ordersQuantity",orders.getOrdersQuantity());
        jsonObject.put("ordersPrice",orders.getOrdersPrice());
        jsonObject.put("consignee",orders.getConsignee());
        jsonObject.put("address",orders.getAddress());
        jsonObject.put("ordersState",orders.getOrdersState());
        return jsonObject;
    }

    /**
     * 修改订单状态
     * @param oid
     * @return
     */
    @Override
    public boolean updataByState(int oid) {
        //发货数量
        Orders orders = ordersRepository.findByOid(oid);
        int quantity = orders.getOrdersQuantity();
        //库存数量
        Goods goods = goodsRepository.findByGid(orders.getGid());
        Integer stock = goods.getGoodsStock();
        //判断库存数量是否充足，充足才能发货，否则不能
        if (quantity <= stock){
            //库存充足，发货后减去库存
            orders.setOrdersState(2);
            ordersRepository.save(orders);
            System.out.println(stock - quantity);
            goods.setGoodsStock(stock - quantity);
            goodsRepository.save(goods);
            return true;
        }else {
            return false;
        }
    }
}
